// 地图相关功能

// 全局变量声明已移至core.js，此处删除
// let currentLocationMapInstance = null;
// let orderRouteMapInstance = null;

// 初始化当前位置地图
function initCurrentLocationMap() {
    if (typeof AMap === "undefined") {
        console.error("AMap SDK not loaded!");
        return;
    }

    if (currentLocationMapInstance) {
        currentLocationMapInstance.destroy();
    }

    currentLocationMapInstance = new AMap.Map('currentLocationMap', {
        resizeEnable: true,
        zoom: 13
    });

    // 如果有当前位置，在地图上显示
    if (currentDeliveryPerson && currentDeliveryPerson.currentLocation) {
        const longitude = currentDeliveryPerson.currentLocation[0];
        const latitude = currentDeliveryPerson.currentLocation[1];
        updateCurrentLocationOnMap(longitude, latitude);
    }
}

// 更新当前位置地图
function updateCurrentLocationOnMap(longitude, latitude) {
    if (!currentLocationMapInstance) return;

    // 清除现有标记
    currentLocationMapInstance.clearMap();

    // 添加新标记
    const marker = new AMap.Marker({
        position: new AMap.LngLat(longitude, latitude),
        title: '当前位置'
    });

    currentLocationMapInstance.add(marker);
    currentLocationMapInstance.setCenter([longitude, latitude]);
}

// 初始化订单路线地图
function initOrderRouteMap(pathCoordinates) {
    if (typeof AMap === "undefined") {
        console.error("AMap SDK not loaded!");
        return;
    }

    if (orderRouteMapInstance) {
        orderRouteMapInstance.destroy();
    }

    const mapContainer = document.getElementById('orderRouteMap');

    if (!pathCoordinates || pathCoordinates.length === 0) {
        mapContainer.innerHTML = '<p class="text-center p-3">无有效路径数据显示。</p>';
        return;
    }

    mapContainer.innerHTML = '';
    orderRouteMapInstance = new AMap.Map('orderRouteMap', {
        resizeEnable: true,
        zoom: 11,
        center: pathCoordinates[0]
    });

    const polyline = new AMap.Polyline({
        path: pathCoordinates,
        strokeColor: "#0d6efd",
        strokeOpacity: 0.9,
        strokeWeight: 6,
        strokeStyle: "solid",
        showDir: true
    });

    orderRouteMapInstance.add(polyline);

    if (pathCoordinates.length > 0) {
        // 起点标记
        const startMarker = new AMap.Marker({
            position: new AMap.LngLat(pathCoordinates[0][0], pathCoordinates[0][1]),
            title: '起点',
            icon: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png'
        });
        
        // 终点标记
        const endMarker = new AMap.Marker({
            position: new AMap.LngLat(
                pathCoordinates[pathCoordinates.length-1][0], 
                pathCoordinates[pathCoordinates.length-1][1]
            ),
            title: '终点',
            icon: 'https://webapi.amap.com/theme/v1.3/markers/n/end.png'
        });
        
        orderRouteMapInstance.add([startMarker, endMarker]);
        
        // 自动调整视图以包含所有标记和路线
        orderRouteMapInstance.setFitView();
    }
}